package com.express.sys.service.impl;

import com.express.entity.Permission;
import com.express.service.GenericDao;
import com.express.service.impl.GenericServiceImpl;
import com.express.sys.service.PermissionService;
import org.springframework.stereotype.Service;
import com.express.sys.mapper.PermissionMapper;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 权限Service实现类
 *
 * @author zhouling
 * @since 2018年6月10日 下午12:05:03
 */
@Service
public class PermissionServiceImpl extends GenericServiceImpl<Permission, String> implements PermissionService {

	@Resource
	private PermissionMapper permissionMapper;


	@Override
	public GenericDao<Permission, String> getDao() {
		return permissionMapper;
	}

	public List getRolePermission(String roleId) {
		return null;
	}

	@Override
	public List<Permission> listMenu() {
		List<Permission> list = this.permissionMapper.selectMenuList();
		List<Permission> result = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			if (!isChild((Permission) list.get(i), result)) {
				result.add(list.get(i));
			}
		}
		return result;
	}

	private boolean isChild(Permission p, List<Permission> result) {
		boolean isChild = false;
		for (int j = 0; j < result.size(); j++) {
			if (p.getParentId() == ((Permission) result.get(j)).getId()) {
				((Permission) result.get(j)).getChildren().add(p);
				return true;
			}
			if ((((Permission) result.get(j)).getChildren().size() > 0) &&
					(isChild(p, ((Permission) result.get(j)).getChildren()))) {
				return true;
			}
		}
		return false;
	}
	@Override
	public void add(Permission permission) {
		this.permissionMapper.insertSelective(permission);
	}
	@Override
	public int update(Permission permission) {
		this.permissionMapper.updateByPrimaryKeySelective(permission);
		return 1;
	}
	@Override
	public void delete(int id) {
		this.permissionMapper.deleteByPrimaryKey(Integer.valueOf(id));
	}

	@Override
	public boolean checkCode(Permission permission) {
		List<Permission> list = this.permissionMapper.checkCode(permission);
		if ((list != null) && (list.size() > 0)) {
			return true;
		}
		return false;
	}
}
